package com.msb.controller;


import com.msb.dto.UserDTO;
import com.msb.pojo.Role;
import com.msb.pojo.User;
import com.msb.pojo.UserRole;
import com.msb.service.RoleService;
import com.msb.service.UserRoleService;
import com.msb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chshh
 * @since 2022-10-21
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService service;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @GetMapping("/query")
    public String query(User user, Model model) throws Exception{
        List<User> list = service.list();
        System.out.println(list);
        model.addAttribute("list",list);
        return "user";
    }

    @RequestMapping("/userDispatch")
    public String userDispatch(Integer userId, Model model, HttpSession session) throws  Exception{
        // 当前的请求是要更新用户数据，需要更加用户编号查询出用户的详细信息
        if(userId != null && userId > 0){
            User user = service.getById(userId);
            session.setAttribute("userId",userId);
            model.addAttribute("user",user);
        }

        // 查询所有的角色信息
        List<Role> list = roleService.list();
        model.addAttribute("roles",list);
        if (userId != null && userId > 0){
            return "updateUser1";
        }else {
            return "updateUser";
        }

    }

    @PostMapping("/saveOrUpdate")
    public String saveOrUpdate(UserDTO userDTO,HttpSession session) throws Exception{

        service.saveOrUpdate(userDTO,session);
        return "redirect:query";
    }

    @GetMapping("/delUser")
    public String delUser(Integer userId) throws Exception{
        boolean b = service.removeById(userId);

        return "redirect:query";
    }


}

